import { action, observable } from 'mobx';
import { message } from 'antd';
import loginServer from '../services/login';
import Base from './base';
import config from '../config';

const { getCode, pollingToken, login, pollingLogin } = loginServer;
const { baseUrl } = config;

export default class LoginState extends Base {

    @observable scanToLogin = false;
    @observable imgepath;

    @action
    async getCode(callback) {
        const data = await getCode();

        if (!data.data) {
            message.error('请求二维码错误');
            return;
        }

        const { imgepath, key } = data.data;
        this.imgepath = `${baseUrl}/file/${imgepath}`;
        // 开始轮询
        let timer = setInterval(async () => {
            if (!this.scanToLogin) {
                clearInterval(timer);
                timer = null
                return;
            }
            try {
                const tokenData = await pollingToken({ key });
                if (tokenData.data && tokenData.data.token) {
                    // 保存token和登录腾信云聊天平台的签名
                    window.localStorage.setItem('pollKey', key);
                    window.localStorage.setItem('userId', tokenData.data.userid);
                    // 需要退出登录的时候清除 现在暂时不需要
                    window.localStorage.setItem('token', tokenData.data.token);
                    window.localStorage.setItem('userSig', tokenData.data.sig);
                    clearInterval(timer);
                    callback && callback(tokenData.data.token);
                }
            } catch (e) {
                clearInterval(timer);
                timer = null
            }
        }, 1000);
    }

    @action
    async login(callback) {
        const key = window.localStorage.getItem('pollKey');
        const userid = window.localStorage.getItem('userId');
        const token = window.localStorage.getItem('token');

        if (!userid) {
            message('暂无用户信息，请扫码登录');
            return;
        }

        const data = await login({ userid, key });

        if (!data.success) {
            message.error('请求登录失败');
            return;
        }

        // 开始轮询
        let timer = setInterval(async () => {
            try {
                const loginData = await pollingLogin({ key });
                if (loginData.success && loginData.data && loginData.data.isconfirmed) {
                    clearInterval(timer);
                    callback && callback(token);
                }
            } catch (e) {
                clearInterval(timer);
                timer = null
            }
        }, 1000);
    }
}